package com.kara.woodAgent.agent.graph.impl;

import cn.hutool.json.JSONUtil;
import com.kara.woodAgent.agent.graph.Next;
import com.kara.woodAgent.agent.graph.Node;
import com.kara.woodAgent.agent.model.ModelProvider;
import com.kara.woodAgent.agent.tool.provider.ToolProvider;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.chat.request.ChatRequest;
import dev.langchain4j.model.chat.request.ResponseFormat;
import dev.langchain4j.model.chat.request.ResponseFormatType;
import dev.langchain4j.model.chat.response.ChatResponse;

import java.util.List;

/**
 * @author tzy
 * @version 1.0
 * @project wood_agent
 * @description
 * @date 2025/6/4 11:30:46
 */
public class ModelNode implements Node<ReactGraphContext> {

    private final ModelProvider modelProvider;

    private final ToolProvider.ToolServiceHolder toolProviderHolder;


    public ModelNode(ModelProvider modelProvider, ToolProvider.ToolServiceHolder toolProviderHolder) {
        this.modelProvider = modelProvider;
        this.toolProviderHolder = toolProviderHolder;
    }

    @Override
    public Next execute(ReactGraphContext context) {

        List<ChatMessage> chatMessages = context.getChatMessages();
        ChatLanguageModel chatModel = modelProvider.getChatModel();

        UserMessage userMessage = UserMessage.from("""
                            #### 注意
                			请你根据当前的执行情况你,分析下一步要做什么,你应该考虑以下问题:
                                1. 您需要创建或完善计划吗？
                                2. 您准备好执行特定步骤了吗？
                                3. 你完成了任务吗？
                            提供推理，然后选择适当的工具工作。
                """);
        chatMessages.add(userMessage);
        ChatRequest request = ChatRequest.builder()
                .toolSpecifications(toolProviderHolder.toolSpecifications())
                .responseFormat(ResponseFormat.builder().type(ResponseFormatType.JSON).build())
                .messages(chatMessages).build();
        ChatResponse chatResponse = chatModel.chat(request);

        AiMessage aiMessage = chatResponse.aiMessage();
        chatMessages.add(aiMessage);

        if (aiMessage.hasToolExecutionRequests()) {
            context.setToolExecutionRequest(aiMessage.toolExecutionRequests());
            return Next.NextNode("tool").step(aiMessage.text() + " " + JSONUtil.toJsonStr(aiMessage.toolExecutionRequests()));
        } else {
            return Next.End().step(aiMessage.text());
        }
    }
}
